const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        //1.登录注册接口
        let writePath = ['/api/login','/api/registry'];
        if(writePath.includes(ctx.path)){
            await next();
        }else{
            //校验token
            let token = ctx.get('token');
            console.log("token====",token)
            try{
                ctx.info = jwt.verify(token,'score');
                await next();
            }catch(e){
                //判断当前错误是否是token的错误
                if(e.name === 'TokenExpiredError' ||  e.name === 'JsonWebTokenError'){
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }
    }
}